package com.niiwoo.civet.trade.service.local.contract;

import com.niiwoo.civet.trade.dao.entity.FadadaContractTemplateFile;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectContract;
import com.niiwoo.civet.trade.dao.entity.ProjectPackageInvestOrder;
import com.niiwoo.civet.trade.dao.mapper.FadadaContractTemplateFileMapperExt;
import com.niiwoo.civet.trade.enums.FadadaContractTemplateEnum;
import com.niiwoo.civet.trade.service.local.contract.vo.IntelligentContractDTO;
import com.niiwoo.tripod.fadada.dto.request.GenerateContractRequestDTO;
import com.niiwoo.tripod.fadada.dto.response.FadadaResponseDTO;
import com.niiwoo.tripod.fadada.enums.SignClientRoleEnum;
import com.niiwoo.tripod.provider.exception.BizException;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 智能投风险提示书
 *
 * @author liaojunjun
 */
@Service
public class IntelligenceRiskPrompt extends AbstractFadadaContract {

    private static final Logger logger = LoggerFactory.getLogger(IntelligenceRiskPrompt.class);

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private ContractBaseService contractBaseService;
    @Autowired
    private FadadaContractTemplateFileMapperExt contractTemplateFileMapperExt;

    @Override
    public ProjectContract contractHandler(FadadaContractTemplateFile contractTemplate, String bizContractNo,
                                           Project project, String userId) throws Exception {
        return null;
    }

    public ProjectContract contractHandler(FadadaContractTemplateEnum.TemplateTypeEnum templateType,
                                           ProjectPackageInvestOrder projectPackageInvestOrder, String investorUserId) throws Exception {
        logger.info("智能投风险提示书处理开始... packageInvestOrderId:{}", projectPackageInvestOrder.getId());

        FadadaContractTemplateFile contractTemplateFile = contractTemplateFileMapperExt.queryFadadaContractTemplateFileByTemplateType(templateType.getType());
        // 借款合同模板不存在
        if (contractTemplateFile == null) {
            throw new BizException("TRD_700007", templateType + " templateType not exists.");
        }

        // 构建智能投风险提示书所需数据
        IntelligentContractDTO contractDTO = contractBaseService.buildIntelligenceContractDTO(investorUserId, projectPackageInvestOrder);

        this.generateContract(contractTemplateFile, contractDTO, projectPackageInvestOrder.getId());

        ProjectContract result = this.signContract(contractTemplateFile, contractDTO, projectPackageInvestOrder.getId());

        this.contractFilling(contractDTO.getContractId());

        logger.info("智能投风险提示书处理结束... packageInvestOrderId:{}", projectPackageInvestOrder.getId());
        return result;
    }

    private void generateContract(FadadaContractTemplateFile contractTemplate, IntelligentContractDTO contractDTO, Long packageInvestOrderId) throws Exception {
        logger.info("智能投风险提示书生成开始... packageInvestOrderId:{}", packageInvestOrderId);

        GenerateContractRequestDTO dto = new GenerateContractRequestDTO();
        dto.setContractId(contractDTO.getContractId());
        dto.setDocTitle(contractTemplate.getTemplateName());
        dto.setTemplateId(contractTemplate.getTemplateId());

        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("investorName", "投资人：" + contractDTO.getUserName());
        parameterMap.put("signDate", DateFormatUtils.format(new Date(), "yyyy年MM月dd日"));
        dto.setParameterMap(parameterMap);
        generateContract(dto);

        logger.info("智能投风险提示书生成结束... packageInvestOrderId:{}", packageInvestOrderId);
    }

    private ProjectContract signContract(FadadaContractTemplateFile contractTemplate, IntelligentContractDTO contractDTO, Long packageInvestOrderId) throws Exception {
        logger.info("法大大合同自动签署-智能投风险提示书 packageInvestOrderId:", packageInvestOrderId);

        // 投资人签署
        String docTitle = contractDTO.getUserName() + "的智能投风险提示书_" + contractDTO.getContractId();
        String transactionId = snowflakeIdWorker.nextId() + "";
        String borrowerCaCertId = contractDTO.getFadadaCacertId();
        String borrowerSignKeyword = "投资人：" + contractDTO.getUserName();
        FadadaResponseDTO fadadaResponse = extSignAuto(transactionId, contractDTO.getContractId(), borrowerCaCertId,
                SignClientRoleEnum.BORROWER.getValue(), docTitle, borrowerSignKeyword);
        logger.info("法大大合同自动签署-智能投风险提示书 投资人签署结束... packageInvestOrderId:{}", packageInvestOrderId);

        return this.buildContractUpdateRecord(contractTemplate.getTemplateId(), contractDTO.getContractId(), transactionId,
                fadadaResponse.getViewUrl(), fadadaResponse.getDownloadUrl());
    }

}
